package com.enjoyireland.hiking;

import java.io.IOException;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;

public class WalkContentProvider extends ContentProvider implements Constants {

	/* ContentProvider constants */
	private static final String AUTHORITY = "com.enjoyireland.hiking.WalkContentProvider";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME);
	public static final int WALKS = 100;
	public static final int WALK_ID = 110;
	private static final UriMatcher sURIMatcher = new UriMatcher(
	        UriMatcher.NO_MATCH);
	static {
	    sURIMatcher.addURI(AUTHORITY, TABLE_NAME, WALKS);
	    sURIMatcher.addURI(AUTHORITY, TABLE_NAME + "/#", WALK_ID);
	}
	
	private WalkDBHelper _walkDB;
	
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri arg0, ContentValues arg1) {
		// TODO Auto-generated method stub
		return null;
	}

    @Override
    public boolean onCreate() {
        _walkDB = new WalkDBHelper(getContext());
        try{
	    	_walkDB.installDB();
		}catch (IOException ioe){
			Log.e(CREATE_DB, ioe.getMessage(), ioe);
		}
        return true;
    }

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
	        String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
	    queryBuilder.setTables(WalkDBHelper.TABLE_NAME);
	 
	    int uriType = sURIMatcher.match(uri);
	    switch (uriType) {
	    case WALK_ID:
	        queryBuilder.appendWhere(WalkDBHelper.ID + "="
	                + uri.getLastPathSegment());
	        break;
	    case WALKS:
	        // no filter
	        break;
	    default:
	        throw new IllegalArgumentException("Unknown URI");
	    }
	 
	    Cursor cursor = queryBuilder.query(_walkDB.getReadableDatabase(),
	            projection, selection, selectionArgs, null, null, sortOrder);
	    cursor.setNotificationUri(getContext().getContentResolver(), uri);
	    return cursor;
	}

	@Override
	public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
		// TODO Auto-generated method stub
		return 0;
	}

}
